﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using HtmlAgilityPack;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace Downloader
{
  public class ForumExtension
  {
    /// <summary>
    /// Removes the obsolete.
    /// </summary>
    /// <param name="innerHtml">The inner HTML.</param>
    /// <returns></returns>
    public static string RemoveObsolete(string innerHtml)
    {
      HtmlDocument doc = new HtmlDocument();
      var deletes = new Dictionary<String, String>()
                      {
                        {"//div/em",".."},
                        {"//div/center/i","../.."},
                        {"//div/a/img","../.."},
                      };
      var ignores = new Dictionary<String, String>()
                      {
                        {"//div[@style]/div/div/table/tr/td/font/b", "//div[@style]/div/div/table/tr/td/font/b/../../../../../../../.."},
                        {"//div/div/div/font","../../.."},
                      };

      doc.LoadHtml(String.Format("<html><body>{0}</body></html>", innerHtml));

      foreach (var ignore in ignores)
      {
        try
        {
          var key = ignore.Key;
          var value = ignore.Value;
          HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(key);
          int count = key.Count(f => f == '/') - 2;

          if (nodes != null)
          {
            // Remove
            foreach (HtmlNode node in nodes)
            {
              var textNode = doc.CreateTextNode();
              textNode.InnerHtml = node.InnerHtml;

              var parentNode = node;
              for (int i = 0; i < count; i++)
              {
                parentNode = parentNode.ParentNode;
              }

              parentNode.ParentNode.ReplaceChild(textNode, parentNode);
            }
          }
        }
        catch (Exception ex)
        {
          MessageBox.Show("Exception: " + ex);
        }
      }

      foreach (var delete in deletes)
      {
        try
        {
          var key = delete.Key;
          var value = delete.Value;
          HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(key);

          if (nodes != null)
          {
            // Remove
            foreach (HtmlNode node in nodes)
            {
              var parentNodes = node.SelectNodes(value);
              if (parentNodes != null && parentNodes.Count == 1)
              {
                var parentNode = parentNodes[0];
                parentNode.InnerHtml = "";
              }

            }
          }
        }
        catch (Exception ex)
        {
          MessageBox.Show("Exception: " + ex);
        }
      }

      return doc.DocumentNode.SelectNodes("//body")[0].InnerHtml;
    }
  }
}
